package be.pluyckx.batteryprogress.utils.calculator;

/**
 * Created by Philip Luyckx on 19/08/13.
 */
public class AverageRealTimeProgressCalculator extends ProgressCalculator {
  private static final String TAG = "ARTPC";

  @Override
  public Result calculate(DataCollection data, ProgressCalculator.Parameters parameters) {
    if (parameters.mOrdered == ProgressCalculator.Parameters.ORDERED_OLD_LOWEST_INDEX) {
      return calculate(data, parameters, data.size() - 1);
    } else {
      return calculate(data, parameters, 0);
    }
  }

  @Override
  public Result calculate(DataCollection data, ProgressCalculator.Parameters parameters, int index) {
    Parameters params = (Parameters) parameters;

    if (data.size() < 2 || index < 0 || index >= data.size()) {
      return null;
    }

    int amount = params.mAmount - 1;

    DataItem oldest;
    DataItem newest;

    if (params.mOrdered == ProgressCalculator.Parameters.ORDERED_OLD_LOWEST_INDEX) {
      if (index == 0) {
        return null;
      }

      if (amount > index) {
        amount = index;
      }

      newest = data.get(index);
      int i = index;
      while (i + amount >= index && data.get(i).getState() == newest.getState()) {
        i--;
      }

      oldest = data.get(i + 1);
    } else {
      if (index + amount > data.size()) {
        amount = data.size() - index - 1;
      }

      newest = data.get(index);
      int i = index;
      while (i - amount <= index && data.get(i).getState() == newest.getState()) {
        i++;
      }

      oldest = data.get(i - 1);
    }

    return average(oldest, newest);
  }

  public static class Parameters extends ProgressCalculator.Parameters {
    public static final String PARAMETER_AMOUNT = "artpc_amount";

    protected int mAmount;

    public Parameters(int ordered, int amount) {
      super(ordered);

      mAmount = amount;
    }
  }
}
